import { Component, OnInit, Injector, Input, AfterViewInit, ViewChild } from '@angular/core';
import { RoleDto, UserServiceProxy, UserDto } from '@shared/service-proxies/service-proxies';

import { ModalComponentBase } from '@shared/component-base';
import { OrganizationUnitsServiceProxy } from 'services/organizationunits/organizationunits.service';
import { NzTreeNode, NzFormatEmitEvent } from 'ng-zorro-antd';
import { FormGroup } from '@angular/forms';

@Component({
  selector: 'app-edit-user',
  templateUrl: './edit-user.component.html',
  styles: [],
  providers: [OrganizationUnitsServiceProxy]
})
export class EditUserComponent extends ModalComponentBase implements OnInit {
  @Input() id: number;
  @ViewChild('treeCom') treeCom;
  @ViewChild('validateForm') validateForm: FormGroup;

  constructor(injector: Injector, private _userService: UserServiceProxy, private organizationunitsService: OrganizationUnitsServiceProxy) {
    super(injector);
  }

  user: UserDto = new UserDto();
  roles: RoleDto[] = null;
  roleList = [];
  //组织单位树
  searchValue;
  nodes = [];
  defaultCheckedKeys = [];

  ngOnInit() {
    this.fetchData();
  }

  fetchData(): void {
    //获取角色
    this._userService.getRoles()
      .subscribe((result) => {
        this.roles = result.items;
        //获取组织单位
        this.organizationunitsService.GetTreesAsync().subscribe((data) => {
          this.nodes = this.handle(data);
        });
        //获取用户明细
        this._userService.getUser(this.id).subscribe((result) => {
          this.user = result;
          //设置组织单位是否选中
          this.defaultCheckedKeys = result.organizationUnitIds;
          //设置角色是否选中
          this.roles.forEach((item) => {
            this.roleList.push({
              label: item.displayName, value: item.name, checked: this.userInRole(item, this.user)
            });
          });
        });
      });
  }
  //递归处理组织单位数据,默认全展开
  handle(data: NzTreeNode[]): NzTreeNode[] {
    data.forEach((item) => {
      item.isExpanded = true;
      let tempTitle = item.title;
      item.title = tempTitle.substring(0, tempTitle.indexOf("（"));
      if (!item.isLeaf) {
        this.handle(item.children);
      }
    })
    return data;
  }

  nzEvent(event: NzFormatEmitEvent): void {

    console.log(event, this.treeCom.getMatchedNodeList().map(v => v.title));
  }

  userInRole(role: RoleDto, user: UserDto): boolean {
    return user.roleNames.indexOf(role.normalizedName) !== -1;
  }

  save(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    if (!this.validateForm.valid) {
      return;
    }
    let tmpRoleNames = [];
    this.roleList.forEach((item) => {
      if (item.checked) {
        tmpRoleNames.push(item.value);
      }
    });

    this.user.roleNames = tmpRoleNames;
    this.user.organizationUnitIds = this.treeCom.getCheckedNodeList().map(v => v.key);
    this.user.surname = this.user.name;
    if (this.user.organizationUnitIds == null || this.user.organizationUnitIds.length <= 0) {
      this.message.error('组织单位必选');
      return
    }
    this._userService.update(this.user)
      .finally(() => { this.saving = false; })
      .subscribe(() => {
        this.notify.success('保存成功');
        this.success();
      });
  }
}
